'use client'

import { useEffect, useState, useMemo } from 'react'
import { useParams } from 'next/navigation'
import { toast } from '@/hooks/use-toast'
import { VmsScript ,AiScript} from '@/types/Model'
import {
  DragDropContext,
  Droppable,
  Draggable,
  DropResult
} from '@hello-pangea/dnd'
import { Button } from '@/components/ui/button'
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogDescription
} from '@/components/ui/dialog'
import { Input } from '@/components/ui/input'
import { Textarea } from '@/components/ui/textarea'
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select'

export default function ScriptsPage() {
  const searchParams = useParams()
  const copy_id = searchParams.copy_id
  const [scripts, setScripts] = useState<VmsScript[]>([])
  const [loading, setLoading] = useState(true)
  const [editingScript, setEditingScript] = useState<VmsScript | null>(null)
  const [isDialogOpen, setIsDialogOpen] = useState(false)
  const [isCreating, setIsCreating] = useState(false)
  const [searchQuery, setSearchQuery] = useState('')
  const [selectedLocation, setSelectedLocation] = useState('all')
  const [selectedStatus, setSelectedStatus] = useState('all')
  const [isGenerating, setIsGenerating] = useState(false)
  const [generatedScripts, setGeneratedScripts] = useState<AiScript[]>([])
  const [showGeneratedDialog, setShowGeneratedDialog] = useState(false)


  // Get unique locations from scripts
  const locations = useMemo(() => {
    if (!Array.isArray(scripts)) return []  // 添加数组检查
    const locs = new Set(scripts.map(script => script.location).filter(Boolean))
    return Array.from(locs)
  }, [scripts])

  const filteredScripts = useMemo(() => {
    if (!Array.isArray(scripts)) return []  // 添加数组检查
    let filtered = scripts
    
    // Filter by search query
    if (searchQuery) {
      filtered = filtered.filter(script => 
        script.caption?.toLowerCase().includes(searchQuery.toLowerCase()) ||
        script.plot?.toLowerCase().includes(searchQuery.toLowerCase()) ||
        script.location?.toLowerCase().includes(searchQuery.toLowerCase())
      )
    }

    // Filter by location
    if (selectedLocation !== 'all') {
      filtered = filtered.filter(script => script.location === selectedLocation)
    }

    // Filter by status
    if (selectedStatus !== 'all') {
      const statusFilter = selectedStatus === 'completed'
      filtered = filtered.filter(script => script.finished === statusFilter)
    }

    return filtered
  }, [scripts, searchQuery, selectedLocation, selectedStatus])

  const fetchScripts = async () => {
    try {
      if (!copy_id) return
      
      const token = localStorage.getItem('token')
      const response = await fetch(`/api/script?copy_id=${copy_id}`, {
        headers: {
          'Authorization': `Bearer ${token}`
        }
      })
      
      if (!response.ok) {
        throw new Error('Failed to fetch scripts')
      }
      
      const data = await response.json()
      setScripts(Array.isArray(data) ? data : [])  // Ensure data is an array
      
      toast({
        title: '数据获取成功',
        description: '脚本列表已加载',
      })
    } catch (error) {
      console.error('Error fetching scripts:', error)
      toast({
        title: '数据获取失败',
        description: error instanceof Error ? error.message : '未知错误',
        variant: 'destructive'
      })
      setScripts([])  // 出错时设置为空数组
    } finally {
      setLoading(false)
    }
  }

  const handleCreateScript = () => {
    setEditingScript({
      id: "",
      copy_id: typeof copy_id === 'string' ? copy_id : '',
      caption: '',
      content: '',
      scene: 0,
      shot: 0,
      shot_angle: '视平',
      shot_move: '固定',
      shot_size: '中景',
      finished: false,
      pxh: scripts.length + 1,
      psh: scripts.length + 1,
      location: '',
      plot: '',
      cch: ''
    })
    setIsCreating(true)
    setIsDialogOpen(true)
  }

  const handleSaveScript = async () => {
    try {
      const token = localStorage.getItem('token')
      const method = isCreating ? 'POST' : 'PUT'
      const response = await fetch('/api/script', {
        method,
        headers: {
          'Authorization': `Bearer ${token}`,
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(editingScript)
      })

      if (!response.ok) {
        throw new Error(isCreating ? 'Failed to create script' : 'Failed to save script')
      }

      toast({
        title: isCreating ? '创建成功' : '保存成功',
        description: isCreating ? '新脚本已创建' : '脚本已更新',
      })
      setIsDialogOpen(false)
      setIsCreating(false)
      fetchScripts()
    } catch (error) {
      console.error('Error saving script:', error)
      toast({
        title: isCreating ? '创建失败' : '保存失败',
        description: error instanceof Error ? error.message : '未知错误',
        variant: 'destructive'
      })
    }
  }

  const handleDragEnd = async (result: DropResult) => {
    if (!result.destination || result.destination.index === result.source.index) return

    // 先更新本地列表
    const items = Array.from(scripts)
    const [reorderedItem] = items.splice(result.source.index, 1)
    items.splice(result.destination.index, 0, reorderedItem)

    const updatedItems = items.map((item, index) => ({
      ...item,
      pxh: index + 1,
      psh: index + 1
    }))

    // 直接更新UI
    setScripts(updatedItems)

    try {
      const token = localStorage.getItem('token')
      const response = await fetch('/api/script/batch', {
        method: 'PUT',
        headers: {
          'Authorization': `Bearer ${token}`,
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(updatedItems)
      })

      if (!response.ok) {
        throw new Error('Failed to update script order')
      }

      toast({
        title: '排序更新成功',
        description: '脚本顺序已更新',
      })

    } catch (error) {
      console.error('Error updating script order:', error)
      toast({
        title: '排序更新失败',
        description: error instanceof Error ? error.message : '未知错误',
        variant: 'destructive'
      })
      // 失败时恢复原顺序
      setScripts(scripts)
    }
  }

  const handleEditScript = (script: VmsScript) => {
    setEditingScript(script)
    setIsCreating(false)
    setIsDialogOpen(true)
  }

  const handleCompleteScript = async (script: VmsScript) => {
    try {
      const token = localStorage.getItem('token')
      const response = await fetch(`/api/script`, {
        method: 'PUT',
        headers: {
          'Authorization': `Bearer ${token}`,
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          ...script,
          finished: true
        })
      })

      if (!response.ok) {
        throw new Error('Failed to complete script')
      }

      toast({
        title: '完成状态更新成功',
        description: '脚本已完成',
      })
      fetchScripts()
    } catch (error) {
      console.error('Error completing script:', error)
      toast({
        title: '完成状态更新失败',
        description: error instanceof Error ? error.message : '未知错误',
        variant: 'destructive'
      })
    }
  }

  useEffect(() => {
    if (copy_id) {
      fetchScripts()
    }
  }, [copy_id])

  if (loading) {
    return (
      <div className="flex justify-center items-center h-64">
        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-gray-900"></div>
      </div>
    )
  }


  const handleGenerateScripts = async () => {
    try {
      setIsGenerating(true)
      const token = localStorage.getItem('token')
      const response = await fetch(`/api/script/generate?copy_id=${copy_id}`, {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${token}`,
          'Content-Type': 'application/json'
        }
      })

      if (!response.ok) {
        throw new Error('Failed to generate scripts')
      }

      const data = await response.json()
      // Ensure data is an array
      console.log(data)
      setGeneratedScripts(Array.isArray(data.scripts) ? data.scripts : [])
      setShowGeneratedDialog(true)
      
      toast({
        title: '脚本生成成功',
        description: '请查看并确认生成的脚本',
      })
    } catch (error) {
      console.error('Error generating scripts:', error)
      toast({
        title: '脚本生成失败',
        description: error instanceof Error ? error.message : '未知错误',
        variant: 'destructive'
      })
      // Set empty array on error
    setGeneratedScripts([])
    } finally {
      setIsGenerating(false)
    }
  }



  const handleBatchCreate = async () => {

    // 为每个生成的脚本添加copy_id
    const scriptsWithCopyId = generatedScripts.map(script => ({
      ...script,
      copy_id: copy_id
    }))
    try {
      const token = localStorage.getItem('token')
      const response = await fetch('/api/script/batch', {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${token}`,
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(scriptsWithCopyId)
      })

      if (!response.ok) {
        throw new Error('Failed to create scripts')
      }

      toast({
        title: '批量创建成功',
        description: '脚本已成功添加',
      })
      setShowGeneratedDialog(false)
      fetchScripts()
    } catch (error) {
      console.error('Error creating scripts:', error)
      toast({
        title: '批量创建失败',
        description: error instanceof Error ? error.message : '未知错误',
        variant: 'destructive'
      })
    }
  }

  const handleDeleteScript = async (script: VmsScript) => {
    try {
      // 二次确认
      const confirmDelete = window.confirm(`确定要删除脚本 "${script.caption}" 吗？此操作无法撤销。`)
      if (!confirmDelete) return

      const token = localStorage.getItem('token')
      const response = await fetch(`/api/script/${script.id}`, {
        method: 'DELETE',
        headers: {
          'Authorization': `Bearer ${token}`
        }
      })

      if (!response.ok) {
        throw new Error('Failed to delete script')
      }

      toast({
        title: '删除成功',
        description: '脚本已删除',
      })
      fetchScripts()
    } catch (error) {
      console.error('Error deleting script:', error)
      toast({
        title: '删除失败',
        description: error instanceof Error ? error.message : '未知错误',
        variant: 'destructive'
      })
    }
  }

  return (
    <div className="container mx-auto flex flex-col h-full">
      <div className="flex-1 p-6">
        <div className="flex flex-col gap-4">
          <div className="flex justify-between items-center">
            <div>
              <h1 className="text-2xl font-bold">Scripts</h1>
              <p className="text-muted-foreground">Manage and run your scripts here.</p>
            </div>
            <div className="flex gap-2">
            <Button 
              variant="outline" 
              onClick={() => window.location.href = `/copy/${copy_id}`}
            >
              返回文案
            </Button>
            <Button 
              variant="destructive" 
              onClick={handleGenerateScripts}
              disabled={isGenerating}
            >
              {isGenerating ? '生成中...' : '生成脚本'}
            </Button>
              <Button onClick={handleCreateScript}>新增脚本</Button>
            </div>
          </div>
          <div className="flex gap-4">
            <Input
              placeholder="搜索脚本..."
              className="max-w-sm"
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
            />
            <Select value={selectedLocation} onValueChange={setSelectedLocation}>
              <SelectTrigger className="w-[180px]">
                <SelectValue placeholder="选择场景" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">所有场景</SelectItem>
                {locations.map((location) => (
                  <SelectItem key={location} value={location ?? ''}>
                    {location ?? ''}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          <Select value={selectedStatus} onValueChange={setSelectedStatus}>
            <SelectTrigger className="w-[180px]">
              <SelectValue placeholder="选择状态" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="all">所有状态</SelectItem>
              <SelectItem value="completed">已完成</SelectItem>
              <SelectItem value="uncompleted">未完成</SelectItem>
            </SelectContent>
          </Select>
          </div>
        </div>
        
        <DragDropContext onDragEnd={handleDragEnd}>
          <Droppable droppableId="scripts">
            {(provided) => (
              <div 
                {...provided.droppableProps}
                ref={provided.innerRef}
                className="space-y-2 mt-4"
              >
                {filteredScripts.map((script, index) => (
                  <Draggable key={script.id} draggableId={script.id} index={index}>
                    {(provided) => (
                      <div
                        ref={provided.innerRef}
                        {...provided.draggableProps}
                        {...provided.dragHandleProps}
                        className="flex items-center justify-between p-4 border rounded-lg"
                      >
                        <div className="flex flex-col gap-1 w-full">
                          <div className="grid grid-cols-8 gap-4 items-center">
                            <div className="col-span-1">
                              {script.pxh && <p className="text-sm text-gray-600">镜号: {script.pxh}</p>}
                            </div>
                            <div className="col-span-1">
                              {script.location && <p className="text-sm text-gray-600">地点: {script.location}</p>}
                            </div>
                            <div className="col-span-1">
                              <h3 className={`text-sm font-semibold ${script.finished ? 'text-gray-400 line-through' : 'text-gray-900'}`}>
                                {script.plot}
                              </h3>
                            </div>
                            <div className="col-span-3">
                              <p 
                                className={`text-sm cursor-pointer ${script.finished ? 'text-gray-400' : 'text-gray-600'}`}
                              >
                                内容：{script.content}
                                <br/>
                                对白：{script.caption}
                              </p>
                            </div>
                            <div className="col-span-1 ">
                              <div className="flex  gap-1">
                                {script.shot_angle && <p className="text-sm text-gray-900">{script.shot_angle}</p>}
                                {script.shot_move && <p className="text-sm text-gray-900">{script.shot_move}</p>}
                                {script.shot_size && <p className="text-sm text-gray-900">{script.shot_size}</p>}
                              </div>
                            </div>
                            <div className="col-span-1">
                              <p className={`text-sm font-medium ${script.finished ? 'text-green-600' : 'text-orange-600'}`}>
                                {script.finished ? '已完成' : '未完成'}
                              </p>
                            </div>
                          </div>
                        </div>
                        <div className="flex gap-2">
                          <Button
                            variant="outline"
                            size="sm"
                            onClick={() => handleEditScript(script)}
                          >
                            编辑
                          </Button>
                          <Button
                            variant={script.finished ? "default" : "outline"}
                            size="sm"
                            onClick={() => handleCompleteScript(script)}
                          >
                            {script.finished ? '已完成' : '完成'}
                          </Button>
                        <Button
                            variant="destructive"
                            size="sm"
                            onClick={() => handleDeleteScript(script)}
                        >
                            删除
                        </Button>
                        
                        </div>
                      </div>
                    )}
                  </Draggable>
                ))}
                {provided.placeholder}
              </div>
            )}
          </Droppable>
        </DragDropContext>

        <Dialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>
          <DialogContent>
            <DialogHeader>
              <DialogTitle>{isCreating ? '新增脚本' : '编辑脚本'}</DialogTitle>
            </DialogHeader>
            {editingScript && (
              <div className="space-y-4">
                <Input
                  value={editingScript.plot}
                  onChange={(e) => setEditingScript({
                    ...editingScript,
                    plot: e.target.value
                  })}
                  placeholder="情节：主体+动作"
                />

                <Input
                    value={editingScript.location || ''}
                    onChange={(e) => setEditingScript({
                      ...editingScript,
                      location: e.target.value
                    })}
                    placeholder="拍摄地点"
                  />
                
                <Textarea
                  value={editingScript.content}
                  onChange={(e) => setEditingScript({
                    ...editingScript,
                    content: e.target.value
                  })}
                  placeholder="脚本内容"
                  rows={6}
                />
                <Textarea
                  value={editingScript.caption}
                  onChange={(e) => setEditingScript({
                    ...editingScript,
                    caption: e.target.value
                  })}
                  placeholder="对白"
                  rows={6}
                />

                <div className="grid grid-cols-2 gap-4">

                <Select
                    value={editingScript.shot_size || ''}
                    onValueChange={(value) => setEditingScript({
                      ...editingScript,
                      shot_size: value
                    })}
                  >
                    <SelectTrigger>
                      <SelectValue placeholder="选择景别" />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="中景">中景</SelectItem>
                      <SelectItem value="近景">近景</SelectItem>
                      <SelectItem value="远景">远景</SelectItem>
                      <SelectItem value="特写">特写</SelectItem>
                    </SelectContent>
                  </Select>

                  <Select
                    value={editingScript.shot_angle || ''}
                    onValueChange={(value) => setEditingScript({
                      ...editingScript,
                      shot_angle: value
                    })}
                  >
                    <SelectTrigger>
                      <SelectValue placeholder="选择镜头角度" />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="视平">视平</SelectItem>
                      <SelectItem value="仰拍">仰拍</SelectItem>
                      <SelectItem value="俯拍">俯拍</SelectItem>
                      <SelectItem value="斜拍">斜拍</SelectItem>
                      <SelectItem value="越肩">越肩</SelectItem>
                    </SelectContent>
                  </Select>

                  <Select
                    value={editingScript.shot_move || ''}
                    onValueChange={(value) => setEditingScript({
                      ...editingScript,
                      shot_move: value
                    })}
                  >
                    <SelectTrigger>
                      <SelectValue placeholder="选择运镜方式" />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="固定">固定</SelectItem>
                      <SelectItem value="横摇">横摇</SelectItem>
                      <SelectItem value="俯仰">俯仰</SelectItem>
                      <SelectItem value="横移">横移</SelectItem>
                      <SelectItem value="升降">升降</SelectItem>
                      <SelectItem value="跟随">跟随</SelectItem>
                      <SelectItem value="环绕">环绕</SelectItem>
                    </SelectContent>
                  </Select>

                 
                  <Select
                    value={editingScript.finished ? '已完成' : '未完成'}
                    onValueChange={(value) => setEditingScript({
                      ...editingScript,
                      finished: value === '已完成'
                    })}
                  >
                    <SelectTrigger>
                      <SelectValue placeholder="选择状态" />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="已完成">已完成</SelectItem>
                      <SelectItem value="未完成">未完成</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
                <Button onClick={handleSaveScript}>{isCreating ? '创建' : '保存'}</Button>
              </div>
            )}
          </DialogContent>
        </Dialog>

        <Dialog open={showGeneratedDialog} onOpenChange={setShowGeneratedDialog}>
        <DialogContent className="max-w-4xl">
          <DialogHeader>
            <DialogTitle>生成的脚本</DialogTitle>
            <DialogDescription>请确认以下生成的脚本</DialogDescription>
          </DialogHeader>
          <div className="space-y-4 max-h-[60vh] overflow-y-auto">
            {generatedScripts.map((script, index) => (
              <div key={index} className="p-4 border rounded-lg">
                <div className="flex flex-col gap-2">
                  <div className="flex gap-4">
                    <p className="font-medium">情节:</p>
                    <p>{script.plot}</p>
                  </div>
                  <div className="flex gap-4">
                    <p className="font-medium">地点:</p>
                    <p>{script.location}</p>
                  </div>
                  <div className="flex gap-4">
                    <p className="font-medium">内容:</p>
                    <p>{script.content}</p>
                  </div>
                  <div className="flex gap-4">
                    <p className="font-medium">对白:</p>
                    <p>{script.caption}</p>
                  </div>
                </div>
              </div>
            ))}
          </div>
          <div className="flex justify-end gap-2">
            <Button variant="outline" onClick={() => setShowGeneratedDialog(false)}>
              取消
            </Button>
            <Button onClick={handleBatchCreate}>
              批量创建
            </Button>
          </div>
        </DialogContent>
      </Dialog>
      </div>
    </div>
  )
}
